package com.xiaoxi.open.common.response;


import com.xiaoxi.open.common.constant.CommonConstant;
import com.xiaoxi.open.common.enumeration.BaseStatusType;
import com.xiaoxi.open.common.enumeration.CommonStatusEnum;
import com.xiaoxi.open.common.exception.BaseException;
import com.xiaoxi.open.common.util.UUIDUtils;
import lombok.Data;
import org.slf4j.MDC;

import java.io.Serializable;

/**
 * 统一响应
 *
 * @author zhoujiale
 */
@Data
public class ResponseData<T> implements Serializable {

    private String requestId;

    private static final long serialVersionUID = 1L;

    private boolean success;

    private String code;

    private String msg;

    private T data;

    public static <T> ResponseData<T> ok() {
        return ok(null);
    }

    public static <T> ResponseData<T> ok(T data) {
        return build(true, CommonStatusEnum.OK.getCode(), CommonStatusEnum.OK.getMsg(), data);
    }

    public static <T> ResponseData<T> fail() {
        return fail(CommonStatusEnum.ERROR, null);
    }

    public static <T> ResponseData<T> fail(String code, String msg) {
        return build(false, code, msg, null);
    }

    public static <T> ResponseData<T> fail(BaseException baseException) {
        return build(false, baseException.getCode(), baseException.getMessage(), null);
    }

    public static <T> ResponseData<T> fail(BaseStatusType baseStatusType) {
        return build(false, baseStatusType.getCode(), baseStatusType.getMsg(), null);
    }

    public static <T> ResponseData<T> fail(BaseStatusType baseStatusType, T data) {
        return build(false, baseStatusType.getCode(), baseStatusType.getMsg(), data);
    }

    public static <T> ResponseData<T> build(boolean success, String code, String msg, T data) {
        ResponseData<T> responseData = new ResponseData<>();
        String requestId = MDC.get(CommonConstant.REQUEST_ID);
        responseData.setRequestId(null == requestId ? UUIDUtils.buildUUID() : requestId);
        responseData.setData(data);
        responseData.setSuccess(success);
        responseData.setCode(code);
        responseData.setMsg(msg);
        return responseData;
    }
}
